package cn.loioi.config;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageHelper;

import tk.mybatis.mapper.code.Style;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

/**
 * 数据库配置
 * @文件 :DataSourceConfig.java
 * @作者 :cn.loioi
 * @创建时间 :2016年10月13日 下午1:11:48
 */
@Order(1)
@Configuration
@ComponentScan("cn.loioi.multi.service.impl")
@PropertySource("classpath:jdbc.properties")
@EnableTransactionManagement(proxyTargetClass = true)
public class DataSourceConfig implements EnvironmentAware, TransactionManagementConfigurer {
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	private Environment env;

	/**
	 * 装载数据库配置文件
	 */
	@Override
	public void setEnvironment(Environment environment) {
		this.env = environment;
	}

	/**
	 * mysql事务管理
	 * @return
	 */
	@Bean
	@Override
	public PlatformTransactionManager annotationDrivenTransactionManager() {
		return new DataSourceTransactionManager(masterDataSource());
	}

	/**
	 * MyBatis 数据连接地址池配置
	 * @throws IOException
	 * @throws SQLException
	 */
	@Bean(name = "masterDataSource", destroyMethod = "close")
	public DruidDataSource masterDataSource() {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setDriverClassName(env.getProperty("jdbc.driverClass", "com.mysql.cj.jdbc.Driver"));
		dataSource.setUrl(env.getProperty("jdbc.url"));
		dataSource.setUsername(env.getProperty("jdbc.username", "root"));
		dataSource.setPassword(env.getProperty("jdbc.password", "root"));
		// 配置初始化大小、最小、最大
		dataSource.setInitialSize(1);
		dataSource.setMinIdle(1);
		dataSource.setMaxActive(20);
		dataSource.setMaxWait(60000);// 配置获取连接等待超时的时间
		dataSource.setTimeBetweenEvictionRunsMillis(60000);// 配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒
		dataSource.setMinEvictableIdleTimeMillis(300000);// 配置一个连接在池中最小生存的时间，单位是毫秒
		dataSource.setDefaultAutoCommit(false);// 禁止自动提交，实现事务管理
		// 拦截配置
		try {
			dataSource.setFilters("stat,wall");
		} catch (SQLException e) {
			logger.error(e.getMessage());
		}
		return dataSource;
	}

	/**
	 * MyBatis配置 :配置sqlSessionFactory
	 * @return
	 * @throws Exception
	 */
	@Bean(name = "masterSqlSessionFactory")
	public SqlSessionFactory masterSqlSessionFactory() throws Exception {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(masterDataSource());
		sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:cn/loioi/multi/mysql/mapper/**/*.xml"));
		// 设置 分页拦截器
		Interceptor interceptor = new PageHelper();
		Properties properties = new Properties();// 分页拦截器配置内容
		properties.setProperty("dialect", "mysql");
		interceptor.setProperties(properties);
		sqlSessionFactoryBean.setPlugins(new Interceptor[] { interceptor });
		return sqlSessionFactoryBean.getObject();
	}

	@Bean(name = "masterMapperScannerConfigurer")
	public MapperScannerConfigurer masterMapperScannerConfigurer() {
		MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
		mapperScannerConfigurer.setSqlSessionFactoryBeanName("masterSqlSessionFactory");
		mapperScannerConfigurer.setBasePackage("cn.loioi.multi.mysql.been");
		mapperScannerConfigurer.getMapperHelper().getConfig().setIDENTITY("MYSQL");
		mapperScannerConfigurer.getMapperHelper().getConfig().setStyle(Style.normal);
		return mapperScannerConfigurer;
	}
}